package com.mc2.docapp.disabilityassessmenttool;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mc2.docapp.disabilityassessmenttool.ConginitalDef.Class_Conginital_Deficiency_component;
import com.mc2.docapp.disabilityassessmenttool.Misc.InputFilterMinMax;
import com.mc2.docapp.disabilityassessmenttool.UpperLimb.CustDataType;
import com.mc2.docapp.disabilityassessmenttool.utils.MailerObject;
import com.mc2.docapp.disabilityassessmenttool.utils.SendMailTLS;

import java.util.HashSet;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;

import static com.mc2.docapp.disabilityassessmenttool.utils.Statics.getEditTexts;
import static com.mc2.docapp.disabilityassessmenttool.utils.Statics.router;


public class CongenitalDeficiencies extends Activity {
    private static final int id = Activities.CONGINITAL_DEFICIENCIES;

    EditText congenitalDefValueLEFT;
    EditText congenitalDefValueRIGHT;

    EditText clubfootLEFT;
    EditText clubfootRIGHT;
    //db instance
    private Realm realm;

    public Class_Conginital_Deficiency_component class_conginital_deficiency_component= new Class_Conginital_Deficiency_component();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_congenital_deficiencies);

        congenitalDefValueLEFT    = (EditText) findViewById(R.id.congenitalDefValueLEFT);
        congenitalDefValueRIGHT   = (EditText) findViewById(R.id.congenitalDefValueRIGHT);
        clubfootLEFT              = (EditText) findViewById(R.id.clubfootLEFT);
        clubfootRIGHT             = (EditText) findViewById(R.id.clubfootRIGHT);
        initRealmDB();
        loadPrevData();
        sanitizeInputs();

        Button saveNnextButton = (Button) findViewById(R.id.saveAndNext);
        saveNnextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                class_conginital_deficiency_component.setTransverse(new CustDataType(Integer.parseInt(IfNull(congenitalDefValueRIGHT.getText().toString(), "0")),
                        Integer.parseInt(IfNull(congenitalDefValueLEFT.getText().toString(), "0")), 0d, 0, 0));

                class_conginital_deficiency_component.setClubfoot(new CustDataType(Integer.parseInt(IfNull(clubfootRIGHT.getText().toString(), "0")),
                        Integer.parseInt(IfNull(clubfootLEFT.getText().toString(), "0")), 0d, 0, 0));

                //DO Calculation
                double a = class_conginital_deficiency_component.getTransverse().getActual_left();
                double b = class_conginital_deficiency_component.getTransverse().getActual_right();
                double c = class_conginital_deficiency_component.getClubfoot().getActual_left();
                double d = class_conginital_deficiency_component.getClubfoot().getActual_right();
                double step1;
                double step2;
                double step3;

                step1 = calByFormula(a,b);
                step2 = calByFormula(step1,c);
                step3 = calByFormula(step2,d);

                class_conginital_deficiency_component.setCalculation(step3);
                NewPatient.finalDto.setCongenitalDeficiencies(class_conginital_deficiency_component);

                realm.beginTransaction();
                realm.delete(Class_Conginital_Deficiency_component.class);
                realm.insert(class_conginital_deficiency_component);
                realm.commitTransaction();
                try {
                    String str = new ObjectMapper().writeValueAsString(class_conginital_deficiency_component).toString();
//                    SendMailTLS.getMailer().sendMail(new MailerObject("saurab.hbhumkar@gmail.com", "MC2 Docapp", "str"));
                } catch (Exception e) {
                    System.out.println();
                }


                Intent intent = new Intent(CongenitalDeficiencies.this, router(CongenitalDeficiencies.class));
                startActivity(intent);
            }
        });

        Button clearAll = (Button) findViewById(R.id.clear);
        clearAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashSet<EditText> views = new HashSet<>();
                getEditTexts((ViewGroup) findViewById(R.id.activity_main), views);
                for (EditText h : views)
                    h.setText("");
            }
        });

    }

    private double calByFormula(double a, double b) {
        if (a < b) {
            a = a + b;
            b = a - b;
            a = a - b;
        }
        return (a + (((90 - a) * b) / 90.0));
    }

    public void sanitizeInputs() {
        congenitalDefValueLEFT.setFilters(new InputFilter[]{new InputFilterMinMax("0", "90")});
        congenitalDefValueRIGHT.setFilters(new InputFilter[]{new InputFilterMinMax("0", "90")});

        clubfootLEFT.setFilters(new InputFilter[]{new InputFilterMinMax("0", "40")});
        clubfootRIGHT.setFilters(new InputFilter[]{new InputFilterMinMax("0", "40")});
    }

    public String IfNull(String value, String defaultValue) {
        if(value == null || value.isEmpty()) {
            return defaultValue;
        } else {
            return  value;
        }
    }

    private void initRealmDB() {
        Realm.init(getApplicationContext());
        // realm = Realm.getDefaultInstance();
        RealmConfiguration config = new RealmConfiguration.Builder().name(id+".realm").build();
        realm = Realm.getInstance(config);
    }

    private void loadPrevData() {
        final RealmResults<Class_Conginital_Deficiency_component> dtos = realm.where(Class_Conginital_Deficiency_component.class).findAll();
//        .equalTo("id",id).findAll();
        System.out.println();
        try {
            //apply ui
            //
            //mapUI(new Class_Conginital_Deficiency_component().strip(dtos.get(0)));
            //
            //realm.beginTransaction();
            //dtos.get(0).deleteFromRealm();
            //realm.commitTransaction();
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
            //no prev data found
        }
    }

    private void mapUI(Class_Conginital_Deficiency_component oldData) {
        congenitalDefValueLEFT.setText(String.valueOf((long) (oldData.getTransverse().getActual_left())));
        congenitalDefValueRIGHT.setText(String.valueOf((long)(oldData.getTransverse()).getActual_right()));

        clubfootLEFT.setText(String.valueOf((long) (oldData.getClubfoot().getActual_left())));
        clubfootRIGHT.setText(String.valueOf((long) (oldData.getClubfoot().getActual_right())));
    }
}
